package com.banyuan.fiilter;
/*
 *   登陆权限过滤器
 * */

import com.banyuan.domain.Author;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1、有一些访问地址，不需要登陆都可以访问，就直接放行
        //登陆：/author/loginPage,/author/login
        //注册：/author/registerPage,/author/register
        //静态资源全部要放行 /author/css,/author/images,/author/js,/author/img,,/author/lib,,/author/skin
        //验证码：/author/getImageCode

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/loginPage") || requestURI.contains("/login")
        || requestURI.contains("/registerPage") || requestURI.contains("/register")
        || requestURI.contains("/getImageCode") || requestURI.contains("/css")
        || requestURI.contains("/images") || requestURI.contains("/img")
        || requestURI.contains("/js") || requestURI.contains("/lib")
        || requestURI.contains("/skin") ) {

            // 放行
            filterChain.doFilter(request,servletResponse);

            //其他访问链接，全部要登陆的
        } else {
            HttpSession session = request.getSession();
            Author author = (Author) session.getAttribute("author");



            // 如果登陆的话，author就不会等于null，因为已经存储进去了
            if (author != null) {
                //2.1 如果登陆了，就直接执行调用链
                filterChain.doFilter(request,servletResponse);
            } else {
                //2.2如果没有登陆，就转发到login.jsp去，让用户去登陆
                request.getRequestDispatcher("/WEB-INF/pages/author/login.jsp").forward(request,servletResponse);

            }


        }




        //需要拦截的 ，如果已经登陆的，就放行，没登陆的让他去登陆

    }

    @Override
    public void destroy() {

    }
}
